package com.firefightingiot.firefightingiot.web.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.firefightingiot.firefightingiot.common.base.BaseService;
import com.firefightingiot.firefightingiot.model.UltrasonicDevice;
import com.firefightingiot.firefightingiot.model.UltrasonicGroup;
import com.firefightingiot.firefightingiot.support.model.RespEntity;
import com.firefightingiot.firefightingiot.support.mybatisplus.QueryWrapper;
import com.firefightingiot.firefightingiot.support.utils.requestutil.HttpRequestUtil;
import com.firefightingiot.firefightingiot.web.mapper.UltrasonicDeviceMapper;
import com.firefightingiot.firefightingiot.web.mapper.UltrasonicGroupMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author: YangYu
 * @ClassName: UltrasonicService
 * @Date: Created in 9:15 2022/10/8
 * @Description: 超声波水表服务
 */
@Service
public class UltrasonicService extends BaseService {

    @Resource
    private UltrasonicGroupMapper ultrasonicGroupMapper;
    @Resource
    private UltrasonicDeviceMapper ultrasonicDeviceMapper;
    /**
     * @Author YangYu
     * @Description 组新增、编辑
     * @Date Created in 9:23 2022/10/8
     * @Param [jsonParam]
     */

    public RespEntity groupAddOrUpdate(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(new JSONObject(), "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        String businessId = "";
        if (StrUtil.isNotBlank(jsonParam.getStr("businessId")) || jsonParam.getStr("businessId") != null){
            businessId = jsonParam.getStr("businessId");
        }else {
            businessId = homeId;
        }
        UltrasonicGroup ultrasonicGroup = new UltrasonicGroup();
        ultrasonicGroup.setBusinessId(businessId);
        if (jsonParam.containsKey("id")){
            ultrasonicGroup.setId(jsonParam.getStr("id"));
            ultrasonicGroup.setName(jsonParam.getStr("name"));
            ultrasonicGroupMapper.updateById(ultrasonicGroup);
        }else {
            ultrasonicGroup.setId(UUID.randomUUID().toString());
            ultrasonicGroup.setName(jsonParam.getStr("name"));
            ultrasonicGroupMapper.insert(ultrasonicGroup);
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 组删除
     * @Date Created in 9:23 2022/10/8
     * @Param [jsonParam]
     */

    public RespEntity groupDel(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(new JSONObject(), "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        if (StrUtil.isNotBlank(jsonParam.getStr("id"))){
            ultrasonicGroupMapper.deleteById(jsonParam.getStr("id"));
        }else {
            return RespEntity.fail("id不能为空");
        }
        return RespEntity.success();
    }
    /**
     * @Author YangYu
     * @Description 组列表
     * @Date Created in 9:23 2022/10/8
     * @Param [jsonParam]
     */

    public RespEntity groupList(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(new JSONObject(), "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        String businessId = "";
        if (StrUtil.isNotBlank(jsonParam.getStr("businessId")) || jsonParam.getStr("businessId") != null){
            businessId = jsonParam.getStr("businessId");
        }else {
            businessId = homeId;
        }
        List<UltrasonicGroup> groupList = ultrasonicGroupMapper.selectList(new QueryWrapper<UltrasonicGroup>().eq("business_id",businessId));
        return RespEntity.success(groupList);
    }

    /**
     * @Author YangYu
     * @Description 超声波设备新增、编辑
     * @Date Created in 16:33 2022/10/8
     * @Param [jsonParam]
     */

    public RespEntity ultrasonicDeviceAddOrUpdate(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(new JSONObject(), "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        String businessId = "";
        if (StrUtil.isNotBlank(jsonParam.getStr("businessId")) || jsonParam.getStr("businessId") != null){
            businessId = jsonParam.getStr("businessId");
        }else {
            businessId = homeId;
        }
        //rest请求单位详情接口，获取单位信息
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("id", businessId);
        com.alibaba.fastjson.JSONObject businessDetail = makeData(jsonParamN, "businessJava", "config", "getBusinessDetailNoToken", "business");
        if (StrUtil.isNotBlank(businessDetail.getString("methodErrorFlag")))
            return RespEntity.fail(businessDetail.getString("msg"));
        jsonParamN.put("homeId",businessDetail.getString("orgId"));
        //rest请求获取所有的机构id
        com.alibaba.fastjson.JSONObject orgIds = makeDataForToken(jsonParamN, "systemsetup", "config", "orgAllListJava", "systemsetup");
        UltrasonicDevice ultrasonicDevice =  new UltrasonicDevice();
        ultrasonicDevice.setBusinessId(businessId);
        ultrasonicDevice.setBusinessName(businessDetail.getString("name"));
        ultrasonicDevice.setAllId(orgIds.getString("orgIds"));
        ultrasonicDevice.setDeviceClassify(jsonParam.getStr("deviceClassify"));
        ultrasonicDevice.setName(jsonParam.getStr("name"));
        ultrasonicDevice.setNumber(jsonParam.getStr("number"));
        ultrasonicDevice.setTransDeviceCode(jsonParam.getStr("transDeviceCode"));
        ultrasonicDevice.setInstalltime(jsonParam.getStr("installtime"));
        ultrasonicDevice.setPosition(jsonParam.getStr("position"));
        ultrasonicDevice.setProductId(jsonParam.getStr("productId"));
        ultrasonicDevice.setDeviceType(jsonParam.getStr("deviceType"));
        ultrasonicDevice.setGroupId(jsonParam.getStr("groupId"));
        ultrasonicDevice.setCurrentstate("1");
        ultrasonicDevice.setNormalUpdateTime(DateUtil.now());
        ultrasonicDevice.setLon(jsonParam.getStr("lon"));
        ultrasonicDevice.setLat(jsonParam.getStr("lat"));
        if (jsonParam.containsKey("id")){
            ultrasonicDevice.setId(jsonParam.getStr("id"));
            UltrasonicDevice ultrasonicDeviceOld = ultrasonicDeviceMapper.selectById(jsonParam.getStr("id"));
            if (!ultrasonicDeviceOld.getNumber().equals(jsonParam.getStr("number"))){
                int count = ultrasonicDeviceMapper.selectCount(new QueryWrapper<UltrasonicDevice>().eq("number",jsonParam.getStr("number")));
                if (count > 0){
                    return RespEntity.fail("设备号已存在");
                }
            }
            ultrasonicDeviceMapper.updateById(ultrasonicDevice);
        }else {
            ultrasonicDevice.setId(UUID.randomUUID().toString());
            int count = ultrasonicDeviceMapper.selectCount(new QueryWrapper<UltrasonicDevice>().eq("number",jsonParam.getStr("number")));
            if (count > 0){
                return RespEntity.fail("设备号已存在");
            }
            ultrasonicDeviceMapper.insert(ultrasonicDevice);
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 超声波设备删除
     * @Date Created in 16:33 2022/10/8
     * @Param [jsonParam]
     */

    public RespEntity ultrasonicDeviceDel(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(new JSONObject(), "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        if (StrUtil.isNotBlank(jsonParam.getStr("id"))){
            ultrasonicDeviceMapper.deleteById(jsonParam.getStr("id"));
        }else {
            return RespEntity.fail("id不能为空");
        }
        return RespEntity.success();
    }
    /**
     * @Author YangYu
     * @Description 超声波设备详情
     * @Date Created in 16:33 2022/10/8
     * @Param [jsonParam]
     */
    public RespEntity ultrasonicDeviceDetail(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(new JSONObject(), "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        if (StrUtil.isBlank(jsonParam.getStr("id"))){
            return RespEntity.fail("id不能为空");
        }
        UltrasonicDevice ultrasonicDevice = ultrasonicDeviceMapper.selectById(jsonParam.getStr("id"));
        return RespEntity.success(ultrasonicDevice);
    }
    /**
     * @Author YangYu
     * @Description 超声波设备分页列表
     * @Date Created in 17:12 2022/10/8
     * @Param [jsonParam]
     */

    public RespEntity ultrasonicDeviceListPage(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(new JSONObject(), "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");
        if (StrUtil.isBlank(jsonParam.getStr("businessId")) || jsonParam.getStr("businessId") == null){
             jsonParam.put("businessId",homeId);
        }
        Page<UltrasonicDevice> page = new Page<>(jsonParam.getInt("page"), jsonParam.getInt("limit"));
        IPage<UltrasonicDevice> pageList = ultrasonicDeviceMapper.ultrasonicDeviceListPage(page, jsonParam);
        Map<String, Object> data = new HashMap<>();
        data.put("totalSize", pageList.getTotal());//总条数
        data.put("pageSize", pageList.getSize());//每页展示多少条
        data.put("currentPage", pageList.getCurrent());//当前页
        data.put("Items", pageList.getRecords());//数据
        data.put("pages", pageList.getPages());//总页数
        data.put("currentSize", pageList.getRecords().size());//当前页多少条
        return RespEntity.success(data);
    }

    public static void main(String[] args) {

        List<String> strings = new ArrayList<>();
        strings.add("1");
        strings.add("2");
        strings.add("3");
        strings.add("4");
        strings.add("5");
        JSONArray jsonArray = new JSONArray();
        int i = 0;
        for (String s :strings){
            jsonArray.add(s);
            if (jsonArray.size()==2){
                System.out.println(jsonArray);
                jsonArray.clear();
            }
        }
        System.out.println(jsonArray);
    }
}
